﻿// 2025/10/14: 首个版本

using System;
using Avalonia.Threading;
using ASEva;
using ASEva.UIAvalonia;

namespace CommonSource
{
    partial class BusyBanner : DialogPanel
    {
        public BusyBanner() // For designer
        {
            InitializeComponent();
        }

        public BusyBanner(string busyReason)
        {
            InitializeComponent();
            SetFixMode(500, 50, false);

            curBusyReason = refineBusyReason(busyReason);
            label.Content = curBusyReason + waitNotice;

            var timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(20);
            timer.Tick += delegate
            {
                var isReadyResult = AgencyLocal.IsReady();
                var newBusyReason = refineBusyReason(isReadyResult.Item2);
                if (isReadyResult.Item1)
                {
                    timer.Stop();
                    Close();
                }
                if (newBusyReason != curBusyReason)
                {
                    curBusyReason = newBusyReason;
                    label.Content = curBusyReason + waitNotice;
                }
            };
            timer.Start();
        }

        private String refineBusyReason(String busyReason)
        {
            busyReason = String.IsNullOrEmpty(busyReason) ? defaultBusyReason : busyReason.Trim();
            if (busyReason.EndsWith(".") || busyReason.EndsWith("。")) busyReason = busyReason.Substring(0, busyReason.Length - 1);
            return busyReason;
        }

        private String curBusyReason;
        private String defaultBusyReason = AgencyLocal.GetAppLanguage() == Language.Chinese ? "系统繁忙" : "System busy";
        private String waitNotice = AgencyLocal.GetAppLanguage() == Language.Chinese ? "，请稍候..." : ". Please wait...";
    }

    class BusyMonitor
    {
        public async void Update()
        {
            if (showingBanner) return;

            var isReadyResult = AgencyLocal.IsReady();
            var isBusy = !isReadyResult.Item1;
            var busyReason = isReadyResult.Item2;

            if (busyStartTime == null)
            {
                if (isBusy) busyStartTime = DateTime.Now;
            }
            else
            {
                if (isBusy)
                {
                    var curTime = DateTime.Now;
                    if (curTime < busyStartTime.Value) busyStartTime = curTime;
                    if ((curTime - busyStartTime.Value).TotalMilliseconds > 2500)
                    {
                        var dialog = new BusyBanner(busyReason);
                        showingBanner = true;
                        await App.RunDialog(dialog);
                        showingBanner = false;
                    }
                }
                else busyStartTime = null;
            }
        }

        private DateTime? busyStartTime = null;
        private bool showingBanner = false;
    }
}